package com.video.moderation.service.impl;

import com.video.moderation.entity.SysMember;
import com.video.moderation.entity.model.MemberLogin;
import com.video.moderation.repository.SysMemberRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class MemberNumUserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private SysMemberRepository sysMemberRepository;
    
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysMember member = sysMemberRepository.findSysMemberByAccount(username);
        if (member == null) throw new UsernameNotFoundException("工号或密码错误");
        return new MemberLogin(member.getMemberId(), member.getMemberNum(), member.getPassword(),getMemberAuthority(member.getRole()));
    }
    
    private List<GrantedAuthority> getMemberAuthority(String role) {
        if (role.equals("客服审核员")) return AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_AUDITOR");
        else return AuthorityUtils.commaSeparatedStringToAuthorityList("ROLE_ADMIN");
    }
}
